package cc.rome753.wat;

import org.webrtc.IceCandidate;

/**
 * 模拟信令服务器，传输 sdp 和 ice
 */
public class SignalingServer {

    private static SignalingServer instance;

    public static SignalingServer get() {
        if (instance == null) {
            synchronized (SignalingServer.class) {
                if (instance == null) {
                    instance = new SignalingServer();
                }
            }
        }
        return instance;
    }

    private PeerClientFragment local;
    private PeerClientFragment remote;

    private SignalingServer() {
    }

    public boolean join(PeerClientFragment peerClient) {
        if (local == null) {
            local = peerClient;
        } else if (local != peerClient && remote == null) {
            remote = peerClient;
            local.onPeerJoin();
        } else {
            return false;
        }

        return true;
    }

    public void leave(PeerClientFragment peerClient, String msg) {
        if (remote == peerClient) {
            remote = null;
        } else if (local == peerClient) {
            local = remote;
            remote = null;
        }

        if (local != null) {
            local.onPeerLeave(msg);
        }
    }

    public boolean sendSdp(PeerClientFragment peerClient, String sdp) {
        if (local == null || remote == null)
            return false;

        if (peerClient == local) {
            remote.onOfferReceived(sdp);
        } else if (peerClient == remote) {
            local.onAnswerReceived(sdp);
        }
        return true;
    }

    public boolean sendIceCandidate(PeerClientFragment peerClient, IceCandidate candidate) {
        if (local == null || remote == null)
            return false;

        if (peerClient == local) {
            remote.onIceCandidateReceived(candidate);
        } else if (peerClient == remote) {
            local.onIceCandidateReceived(candidate);
        }
        return true;
    }

    public interface Callback {
        void onPeerJoin();

        void onPeerLeave(String msg);

        void onOfferReceived(String data);

        void onAnswerReceived(String data);

        void onIceCandidateReceived(IceCandidate candidate);
    }
}
